package com.wannengbang.cloudleader.invite;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.appconst.Constants;
import com.wannengbang.cloudleader.base.BaseFragment;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.dialog.WXShareDialog;
import com.wannengbang.cloudleader.event.UpDateNameEvent;
import com.wannengbang.cloudleader.utils.QRCodeUtil;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;

import org.greenrobot.eventbus.Subscribe;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 *
 */
public class InviteFragment extends BaseFragment {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    private Unbinder unbinder;
    private UserInfoBean userInfoBean;
    private List<View> mViewList = new ArrayList<>();
    private View view1;
    private View view2;
    private View view3;
    private TextView tvName1;
    private TextView tvName2;
    private TextView tvName3;
    private TextView tvLuckyNumber1;
    private TextView tvLuckyNumber2;
    private TextView tvLuckyNumber3;
    private ImageView ivErweima1;
    private ImageView ivErweima2;
    private ImageView ivErweima3;
    private DemoPageAdapter pageAdapter;
    private Bitmap bitmap = null;
    private Handler mHandler = new Handler();
    private RelativeLayout layout = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_invite, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        registerEventBus();
        return view;
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f)
                .init();
    }

    public void initView() {
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);

        view1 = LayoutInflater.from(mActivity).inflate(R.layout.view_pager_invate3, null);
        view2 = LayoutInflater.from(mActivity).inflate(R.layout.view_pager_invate2, null);
        view3 = LayoutInflater.from(mActivity).inflate(R.layout.view_pager_invate1, null);

        tvName1 = view1.findViewById(R.id.tv_name);
        tvLuckyNumber1 = view1.findViewById(R.id.tv_lucky_number);
        ivErweima1 = view1.findViewById(R.id.iv_erweima);

        tvName2 = view2.findViewById(R.id.tv_name);
        tvLuckyNumber2 = view2.findViewById(R.id.tv_lucky_number);
        ivErweima2 = view2.findViewById(R.id.iv_erweima);

        tvName3 = view3.findViewById(R.id.tv_name);
        tvLuckyNumber3 = view3.findViewById(R.id.tv_lucky_number);
        ivErweima3 = view3.findViewById(R.id.iv_erweima);


        if (userInfoBean != null && userInfoBean.getData() != null) {
            Bitmap mBitmap = QRCodeUtil.createQRCodeBitmap(userInfoBean.getData().getInvite_url(), 480, 480);
            ivErweima1.setImageBitmap(mBitmap);
            tvName1.setText(userInfoBean.getData().getName());
            tvLuckyNumber1.setText(userInfoBean.getData().getLucky_number());

            ivErweima2.setImageBitmap(mBitmap);
            tvName2.setText(userInfoBean.getData().getName());
            tvLuckyNumber2.setText(userInfoBean.getData().getLucky_number());

            ivErweima3.setImageBitmap(mBitmap);
            tvName3.setText(userInfoBean.getData().getName());
            tvLuckyNumber3.setText(userInfoBean.getData().getLucky_number());
        }

        mViewList.add(view1);
        mViewList.add(view2);
        mViewList.add(view3);
        pageAdapter = new DemoPageAdapter();
        viewPager.setAdapter(pageAdapter);
        viewPager.setOffscreenPageLimit(3);
    }

    @Subscribe
    public void onUpDateNameEvent(UpDateNameEvent event) {
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null && userInfoBean.getData() != null) {
            tvName1.setText(userInfoBean.getData().getName());
            tvName2.setText(userInfoBean.getData().getName());
            tvName3.setText(userInfoBean.getData().getName());

            mViewList.clear();
            mViewList.add(view1);
            mViewList.add(view2);
            mViewList.add(view3);
            pageAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.iv_invate_xiazai, R.id.iv_invate_fenxiang, R.id.iv_invate_zuofan, R.id.iv_invate_youfan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_invate_xiazai:
                int position = viewPager.getCurrentItem();
                if (position == 0) {
                    layout = view1.findViewById(R.id.root_bg);
                }
                if (position == 1) {
                    layout = view2.findViewById(R.id.root_bg);
                }
                if (position == 2) {
                    layout = view3.findViewById(R.id.root_bg);
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        saveScreenShot(viewConversionBitmap(layout));
                    }
                });
                break;
            case R.id.iv_invate_fenxiang:
                // SendMessageToWX.Req.WXSceneSession是分享到好友会话
                // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
                position = viewPager.getCurrentItem();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (position == 0) {
                            layout = view1.findViewById(R.id.root_bg);
                            bitmap = viewConversionBitmap(layout);
                        }
                        if (position == 1) {
                            layout = view2.findViewById(R.id.root_bg);
                            bitmap = viewConversionBitmap(layout);
                        }
                        if (position == 2) {
                            layout = view3.findViewById(R.id.root_bg);
                            bitmap = viewConversionBitmap(layout);
                        }
                        WXShareDialog dialog = WXShareDialog.newInstance();
                        dialog.show(getChildFragmentManager(), "dialog");
                        dialog.setOnCallBackListener(type -> {
                            if (1 == type) {
                                wxShare(SendMessageToWX.Req.WXSceneSession, bitmap);
                            } else {
                                wxShare(SendMessageToWX.Req.WXSceneTimeline, bitmap);
                            }
                        });
                    }
                });

                break;
            case R.id.iv_invate_zuofan:
                position = viewPager.getCurrentItem();
                if (position == 0) {
                    viewPager.setCurrentItem(2);
                } else {
                    viewPager.setCurrentItem(position - 1);
                }
                break;
            case R.id.iv_invate_youfan:
                position = viewPager.getCurrentItem();
                if (position == 2) {
                    viewPager.setCurrentItem(0);
                } else {
                    viewPager.setCurrentItem(position + 1);
                }
                break;
        }
    }


    public void wxShare(int sceneType, Bitmap bmp) {
        // 三个参数分别是上下文、应用的appId、是否检查签名（默认为false）
        IWXAPI mWxApi = WXAPIFactory.createWXAPI(mActivity, Constants.WENXIN_KEY, false);
        mWxApi.registerApp(Constants.WENXIN_KEY);


        //初始化 WXImageObject 和 WXMediaMessage 对象
        WXImageObject imgObj = new WXImageObject(bmp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        //设置缩略图
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 120, 120, true);
        bmp.recycle();
        msg.thumbData = bmpToByteArray(thumbBmp, true);

        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        req.scene = sceneType;
        //调用api接口，发送数据到微信
        mWxApi.sendReq(req);

    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 90, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }


    public class DemoPageAdapter extends PagerAdapter {

        // 返回界面数量
        @Override
        public int getCount() {
            return mViewList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        // 添加界面，一般会添加当前页和左右两边的页面
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));
            return mViewList.get(position);
        }

        // 去除页面
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }

    }

    /**
     * view转bitmap
     */
    public Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        v.draw(c);
        return bmp;
    }

    /**
     * 屏幕截图保存
     */
    private void saveScreenShot(Bitmap bitmap) {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
        String filename;//声明文件名
        //以保存时间为文件名
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);
        File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件，第一个参数为路径，第二个参数为文件名
        try {
            outStream = new FileOutputStream(file);//创建输入流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            outStream.close();

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mActivity.sendBroadcast(intent);
            ToastUtil.showShort("保存相册成功");
            Vibrator vibrator = (Vibrator) mActivity.getSystemService(mActivity.VIBRATOR_SERVICE);
            vibrator.vibrate(200);
        } catch (Exception e) {
            ToastUtil.showShort("保存相册失败，可尝试系统截屏保存");
        }
    }
}
